package com.haiyou.dc.thread.test2;

/**
 * 生产者消费者实现方式一：管程法
 */
public class CoTest01 {

    public static void main(String[] args) {
        SysContainer sysContainer = new SysContainer();
        new Producter(sysContainer).start();
        new Customer(sysContainer).start();
    }

}

/**
 * 生产者
 */
class Producter extends Thread {

    SysContainer sysContainer;

    public Producter(SysContainer sysContainer) {
        this.sysContainer = sysContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            sysContainer.push(new Mantou(i));
            System.out.println("生产了" + i + "馒头");
        }

    }
}

/**
 * 消费者
 */
class Customer extends Thread {
    SysContainer sysContainer;

    public Customer(SysContainer sysContainer) {
        this.sysContainer = sysContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Mantou pop = sysContainer.pop();
            System.out.println("消费了" + pop.id + "馒头");
        }
    }
}

/**
 * 馒头
 */
class Mantou {

    public int id;

    public Mantou(int id) {
        this.id = id;
    }
}

/**
 * 缓冲区
 */
class SysContainer {

    //存储容器
    private Mantou[] mantous = new Mantou[10];
    //计数器
    private int count = 0;

    /**
     * 存储生产
     *
     * @param mantou
     */
    public synchronized void push(Mantou mantou) {
        System.out.println("生产count--->" + count);
        if (count == mantous.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        mantous[count] = mantou;
        count++;
        this.notifyAll();
    }

    /**
     * 获取消费
     *
     * @return
     */
    public synchronized Mantou pop() {
        System.out.println("消费count--->" + count);
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        count--;
        return mantous[count];
    }


}